from openai import OpenAI
import json
import os

# 使用百炼的兼容端点
client = OpenAI(
    api_key='sk-80343c1ec74f43bba6a8ad2d01d19068',
    base_url='https://dashscope.aliyuncs.com/compatible-mode/v1'
)

# 配置参数
MODEL_LIST = ["qwen-flash", "qwen-plus"]  # 可用模型列表
MAX_CALLS_PER_MODEL = 100000000000000  # 每个模型最大调用次数
STATE_FILE = "model_state2.json"  # 状态保存文件
def load_state2():
    """加载模型调用状态"""
    if os.path.exists(STATE_FILE):
        with open(STATE_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    else:
        return {
            "current_index": 0,
            "usage_counts": {model: 0 for model in MODEL_LIST}
        }

def save_state2(state):
    """保存模型调用状态"""
    with open(STATE_FILE, "w", encoding="utf-8") as f:
        json.dump(state, f, indent=2)


def get_next_model():
    """返回当前可用模型，记录一次调用，必要时切换到下一个模型"""
    state = load_state2()
    idx = state["current_index"]
    usage = state["usage_counts"]

    while idx < len(MODEL_LIST):
        model = MODEL_LIST[idx]
        if usage[model] < MAX_CALLS_PER_MODEL:
            usage[model] += 1
            break
        else:
            idx += 1  # 当前模型已达上限，尝试下一个模型

    if idx >= len(MODEL_LIST):
        raise Exception("所有模型调用次数都已达上限！")

    # 更新状态并保存
    state["current_index"] = idx
    state["usage_counts"] = usage
    save_state2(state)
    return model
def predict_category_and_brand(product_name):
    """使用通用模型预测商品类目和品牌"""
    try:
        # 获取当前可用模型
        current_model = 'qwen-flash'
        print(f"📋 使用模型: {current_model}")
        # 类目预测
        category_response = client.chat.completions.create(
            model=current_model,  # 使用通用模型
            messages=[
                {
                    "role": "system", 
                    "content": "你是一个电商分类专家，请根据商品名称预测其所属类目，只返回类目名称。"
                },
                {
                    "role": "user",
                    "content": f"请预测商品'{product_name}'的类目"
                }
            ],
            stream=False
        )
        
        # 品牌预测
        brand_response = client.chat.completions.create(
            model=current_model,  # 使用通用模型
            messages=[
                {
                    "role": "system",
                    "content": "你是一个品牌识别专家，请根据商品名称预测其品牌，只返回品牌名称。"
                },
                {
                    "role": "user", 
                    "content": f"请预测商品'{product_name}'的品牌"
                }
            ],
            stream=False
        )
        
        return {
            'category': category_response.choices[0].message.content,
            'brand': brand_response.choices[0].message.content
        }
        
    except Exception as e:
        print(f"预测失败: {e}")
        return None
if __name__ == '__main__':
    # 测试
    products = [
        "TOMMY HILFIGER TOMMY汤米男士2025潮牌春装外套美式休闲潮流春秋季连帽夹克",
    ]

    print("🚀 开始商品预测...")
    print("=" * 50)

    for product in products:
        result = predict_category_and_brand(product)
        if result:
            print(f"\n📦 商品: {product}")
            print(f"   📂 类目: {result['category']}")
            print(f"   🏷️ 品牌: {result['brand']}")
            print("-" * 40)
